package com.fy.proj4_database_basic.service.impl;

import com.fy.proj4_database_basic.mapper.UserMapper;
import com.fy.proj4_database_basic.model.User;
import com.fy.proj4_database_basic.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAllUsers() {
        return userMapper.findAll();
    }

    @Override
    public User findUserById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public User findUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User addUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        return user;
    }

    @Override
    public User updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
        return user;
    }

    @Override
    public boolean deleteUserById(Long id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    public boolean deleteUserByUsername(String username) {
        return userMapper.deleteByUsername(username) > 0;
    }

    @Override
    public List<User> findUsersByPage(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return userMapper.findByPage(offset, pageSize);
    }
}